#include "netlib/net/codec/length_header_codec.h"

#include <string>

#include "netlib/base/logger.h"

void LengthHeaderCodec::Send(const net::TcpConnectionPtr& conn, const std::string& msg) {
	net::Buffer buf;
	buf.Append(msg.c_str(), msg.size());
	int32_t len = msg.size();
	// uint32_t be32 = net::sockets::hostToNetwork32(len);
	// buf.Prepend(&be32, sizeof(uint32_t));
	buf.Prepend(&len, sizeof(len));
	conn->Send(buf.RetrieveAllAsString());
}

void LengthHeaderCodec::OnMessage(const net::TcpConnectionPtr& conn,
                                  net::Buffer* buf,
                                  Timestamp time) {
	while (buf->ReadableBytes() >= kHeaderLen) {
		int32_t len = buf->PeekInt32(); // 已做网络到本地转换
		if (len > 65536 || len < 0) {
			LOG_ERROR << "Invalid Length: " << len;
			conn->Shutdown();
			break;
		}
		if (buf->ReadableBytes() >= kHeaderLen + len) {
			buf->Retrieve(kHeaderLen);
			std::string msg(buf->Peek(), len);
			buf->Retrieve(len);
			msg_callback_(conn, msg, time);
		} else {
			break;
		}
	}
}
